package com.bsh.serviceImpl;

import java.math.BigDecimal;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bsh.api.params.DtoUpgradeGrade;
import com.bsh.mybatis.model.Account;
import com.bsh.mybatis.model.AccountNotice;
import com.bsh.mybatis.model.Payment;
import com.bsh.mybatis.model.User;
import com.bsh.repository.DaoAccount;
import com.bsh.repository.DaoAccountLog;
import com.bsh.repository.DaoAccountNotice;
import com.bsh.repository.DaoPayment;
import com.bsh.repository.DaoUser;
import com.bsh.service.RecommendService;
import com.bsh.service.UpgradeService;
import com.bsh.utils.DesUtils;
import com.bsh.utils.PrimaryGenerater;
import com.bsh.utils.system.AccountLock;

/**
 * 升级会员等级
 * @author jane
 *
 */
@Service
@Transactional
public class UpgradeServiceImpl implements UpgradeService {
	private static Logger log = LoggerFactory.getLogger(UpgradeServiceImpl.class);
	@Autowired
	private DaoUser daoUser;
	@Autowired
	private DaoAccount daoAcc;
	@Autowired
	private DaoAccountLog daoAccLog;
	@Autowired
	private DaoAccountNotice daoNotice;
	@Autowired
	private RecommendService recommendSer;
	@Autowired
	private DaoPayment daoPay;
	

	@Override
	@Transactional
	public DtoUpgradeGrade upgradeMemberBalance(String userName,String paypassword,String level,String ip){
		Integer res = -1;
		DtoUpgradeGrade result = new DtoUpgradeGrade();
		result.setRes(res);
		User userInfo = daoUser.selectByName(userName);
		if(userInfo == null){
			result.setRes(new Integer("-1"));
			result.setMessage("用户不存在");
			return result;
		}
		if( userInfo.getLevel().equals(level) ){
			result.setRes(new Integer("-1"));
			result.setMessage("已经是"+level);
			return result;
		}
		if( level.equals("vip") && userInfo.getLevel().equals("gold") ){
			result.setRes(new Integer("-1"));
			result.setMessage("已经是金钻");
			return result;
		}
		//定价格
		BigDecimal money = new BigDecimal("0");
		if(level.equals("vip")){
			money = new BigDecimal("100");
		}
		if(level.equals("gold")){
			money = new BigDecimal("1000");
		}
		if(money.compareTo(new BigDecimal("0")) <=0){
			result.setRes(new Integer("-1"));
			result.setMessage("金额不正确");
			return result;
		}
		Account accInfo = daoAcc.getUserAccount(userInfo.getId());
		Integer accountId;
		if (accInfo == null) {
			accountId = daoAcc.initUserAcount(userInfo.getId());
		} else {
			accountId = accInfo.getId();
		}
		if( accInfo.getMoney().compareTo(money) == -1){
			//余额不足
			result.setRes(new Integer("-2"));
			result.setMessage("余额不足");
			return result;
		}
		if( paypassword == null){
			result.setRes(new Integer("-1"));
			result.setMessage("密码不能为空");
			return result;
		}
		DesUtils des=new DesUtils();
		String enPassword=des.encryptPassword(paypassword);
		if(accInfo.getPayPassword() ==null){
			result.setRes(new Integer("-3"));
			result.setMessage("账户密码为空");
			return result;
		}
		if(!accInfo.getPayPassword().equals(enPassword)){
			//密码不正确
			result.setRes(new Integer("-4"));
			result.setMessage("密码不正确");
			return result;
		}
		
		boolean isLock1 = AccountLock.getLock(accountId, userInfo.getId());
		if( !isLock1){
			result.setRes(new Integer("-11"));
			return result;
		}
		Integer type = 4; //会员升级
		//升级会员  ,update user, addCloudMoney, recommend ,money, notice two
		
		
				String sn = PrimaryGenerater.getInstance().next();
				
				// 账户变动前记录日志
				daoAccLog.addLog(accountId, sn, ip);
				//扣现金
				res = daoAcc.addMoney(accountId, userInfo.getId(), money.multiply(new BigDecimal("-1")) );
				AccountNotice notice = new AccountNotice();
				notice.setAccountId(accountId);
				notice.setUserid(userInfo.getId());
				notice.setMoney( money.multiply(new BigDecimal("-1")) );// 现金负数
				notice.setTradeType((int) type); //交易类型4
				notice.setSn(sn);// 流水号
	
				notice.setTitle(String.format("升级为%s -%s",level, money));
				notice.setPaymentId(4);// 余额支付 4-Balance
				notice.setIp(ip);
				notice.setIsPaid((byte) 1);// 已付款
				notice.setMoneyType((short) 1);// 现金类型1,
				notice.setCreateTime(new Date());
				// 在查
				Account downAccInfo = daoAcc.selectByPrimaryKey(accountId);
				notice.setMoneyDown(downAccInfo.getMoney()); // 结存现金余额
				notice.setCloudMoneyDown(downAccInfo.getCloudMoney()); // 结存商币余额
				res = daoNotice.insert(notice);
				
				res = daoAcc.addCloudMoney(accountId, userInfo.getId(), money);
				AccountNotice noticeCloud = new AccountNotice();
				noticeCloud.setAccountId(accountId);
				noticeCloud.setUserid(userInfo.getId());
				noticeCloud.setCloudMoney(money);// 商币
	
				noticeCloud.setTradeType((int) type); //4
				noticeCloud.setSn(sn);// 流水号
				String snTemp = PrimaryGenerater.getInstance().next();
				noticeCloud.setCsn(sn);// 这笔转账动作流水号
				noticeCloud.setSn(snTemp);// 唯一流水号
//				noticeCloud.setOperator((int) -1); // -1系统操作
	
				noticeCloud.setTitle(String.format("会员升级获得商币+%s", money));
				noticeCloud.setPaymentId(3);// 系统操作
				noticeCloud.setIp(ip);
				noticeCloud.setIsPaid((byte) 1);// 已付款
				noticeCloud.setMoneyType((short) 0);// 商币类型0,
				noticeCloud.setCreateTime(new Date());
				// 在查
				Account downAccInfoCloud = daoAcc.selectByPrimaryKey(accountId);
				noticeCloud.setMoneyDown(downAccInfoCloud.getMoney()); // 结存现金余额
				noticeCloud.setCloudMoneyDown(downAccInfoCloud.getCloudMoney()); // 结存商币余额
				res = daoNotice.insert(noticeCloud);
				result.setRes(res);
				
//				User userLastCheck = daoUser.selectByName(userName);
//				if(userLastCheck.getLevel().equals(level)){
//					//主动回滚
//					log.error("ERROR_IMP:余额升级主动回滚["+userName+"]"+level+"||"+userLastCheck.getLevel());
//					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//					result.setRes(new Integer("-6"));
//					result.setMessage("已经升级成功，不要重复操作-6");
//					AccountLock.unLock(accountId, userInfo.getId());
//					return result;
//				}
				User record = new User();
				record.setLevel(level);
				record.setId(userInfo.getId());
				res = daoUser.updateByPrimaryKeySelective(record);
				result.setRes(new Integer(res));
				if( res > 0){
					//推荐人返现
					res = recommendSer.memberUpgradeByCash(level, userInfo.getId(), money, sn);
					//解锁
					AccountLock.unLock(accountId, userInfo.getId());
				}else{
					result.setRes(new Integer("-8"));
					result.setMessage("更新失败");
					return result;
				}
				
	
	    return result;
	}

	/**
	 * Api 调用 会员在线支付 升级(只返回流水号) 不处理回调业务
	 */
	@Override
	public DtoUpgradeGrade upgradeMemberOnline(String userName,String paypassword,String level,String ip,String paymentType){
		Integer res = -1;
		DtoUpgradeGrade result =  new DtoUpgradeGrade();
		result.setRes(res);
		User userInfo = daoUser.selectByName(userName);
		if(userInfo == null){
			result.setRes(new Integer("-1"));
			result.setMessage("用户不存在");
			return result;
		}
		if( userInfo.getLevel().equals(level) ){
			result.setRes(new Integer("-1"));
			result.setMessage("已经是"+level);
			return result;
		}
		if( level.equals("vip") && userInfo.getLevel().equals("gold") ){
			result.setRes(new Integer("-1"));
			result.setMessage("已经是金钻");
			return result;
		}
		//定价格
		BigDecimal money = new BigDecimal("0");
		if(level.equals("vip")){
			money = new BigDecimal("100");
		}
		if(level.equals("gold")){
			money = new BigDecimal("1000");
		}
		if(money.compareTo(new BigDecimal("0")) <=0){
			result.setRes(new Integer("-1"));
			result.setMessage("金额不正确");
			return result;
		}
		Account accInfo = daoAcc.getUserAccount(userInfo.getId());
		Integer accountId;
		if (accInfo == null) {
			accountId = daoAcc.initUserAcount(userInfo.getId());
		} else {
			accountId = accInfo.getId();
		}
		if( paypassword == null){
			result.setRes(new Integer("-1"));
			result.setMessage("密码不能为空");
			return result;
		}
		DesUtils des=new DesUtils();
		String enPassword=des.encryptPassword(paypassword);
		if(accInfo.getPayPassword() ==null || !accInfo.getPayPassword().equals(enPassword)){
			//密码不正确
			result.setRes(new Integer("-5"));
			result.setMessage("密码不正确");
			return result;
		}
		
		Payment payment = daoPay.getPaymentByClassName(paymentType);
		if( payment == null){
			result.setRes(new Integer("-1"));
			result.setMessage("支付方式不存在");
			return result;
		}
		if( payment.getOnlinePay() <= 0){
			result.setRes(new Integer("-1"));
			result.setMessage("选择正确在线支付方式");
			return result;
		}
		boolean isLock1 = AccountLock.getLock(accountId, userInfo.getId());
		if(!isLock1){
			result.setRes(new Integer("-11"));
			return result; 
		}
		
		String sn = PrimaryGenerater.getInstance().next();
		Integer type = 4; //会员升级
		//升级会员  add notice and paid is 0
		
		AccountNotice notice = new AccountNotice();
		notice.setAccountId(accountId);
		notice.setUserid(userInfo.getId());
		notice.setMoney( money  );// 现金正数
		notice.setTradeType((int) type); //交易类型4
		notice.setSn(sn);// 流水号

		String desc = String.format(userInfo.getName()+"升级为%s",level);
		String title = String.format(payment.getName()+"转入余额+%s元",money);
		notice.setTitle(title);
		notice.setPaymentId( payment.getId() );
		notice.setIp(ip);
		notice.setIsPaid((byte) 0);// 未付，默认0
		notice.setMoneyType((short) 1);// 现金类型1,
		notice.setCreateTime(new Date());
		// 在查
		Account downAccInfo = daoAcc.selectByPrimaryKey(accountId);
		notice.setMoneyDown(downAccInfo.getMoney()); // 结存现金余额
		notice.setCloudMoneyDown(downAccInfo.getCloudMoney()); // 结存商币余额
		res = daoNotice.insert(notice);

		AccountLock.unLock(accountId, userInfo.getId());
		result.setRes(res);
		result.setSn(sn);
		result.setDesc(desc);
		result.setMoney(money);
	    return result;
	}

	

}
